package org.libarae.communication.response;

import java.io.ByteArrayOutputStream;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.libarae.communication.HTTPUtils;
import org.libarae.communication.XmlParseException;
import org.libarae.communication.common.Message;
import org.libarae.communication.common.Type;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class GetThreadMessageResponse extends Response{
	private Vector<Message> mMessages = new Vector<Message>();
	
	public GetThreadMessageResponse(int status){
		super(Type.GET_THREAD_MESSAGES, status);		
	}
	
	public GetThreadMessageResponse(int status, Vector<Message> mt){
		super(Type.GET_THREAD_MESSAGES, status);		
		setMessages(mt);
	}	
	
	@Override
	public String createXML() throws XmlParseException {
		Document doc;
		try{
			//setup the factory to build the xml
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			doc = documentBuilder.newDocument();
		}
		catch (Exception e) {
			throw new XmlParseException("Error creating XML Builder",e);
		}
		
		//create the xml
		Element rootElement = doc.createElement("type");
		rootElement.setAttribute("typeID", super.getType()+"");
		doc.appendChild(rootElement);
		//user name
		Element node = doc.createElement("mStatus");
		node.setTextContent(getStatus()+"");
		rootElement.appendChild(node);

		node = doc.createElement("mMessages");
		for(Message m : mMessages){
			Element subNode =  doc.createElement("Message");
			m.createXml(doc, subNode);
			node.appendChild(subNode);
		}	
		rootElement.appendChild(node);
		
		//export the xml to a string
		String output = null;
		try {
			ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream();
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(byteArrayOutput);
			transformer.transform(source, result);
			output = byteArrayOutput.toString();
		}
		catch (Exception e) {
			throw new XmlParseException("Error outputting XML to string", e);
		}
		
		//return the string
		return output;
	}

	@Override
	public void decodeXML(Document document) {
		// get the document root and node list
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getChildNodes();

		// set all of the nodes in their proper places
		for (int i = 0; i < nodeList.getLength(); i++) {
			// find what node we have
			String nodeName = nodeList.item(i).getNodeName();
			if (nodeName.equals("mStatus")) {
				setStatus(Integer.parseInt(nodeList.item(i).getTextContent()));
			}
			else if (nodeName.equals("mMessages")) {
				NodeList nodeVector = nodeList.item(i).getChildNodes();
				mMessages = new Vector<Message>();
				for(int p = 0; p < nodeVector.getLength(); p++){
					Message message = new Message();
					message.decodeXML(nodeVector.item(p));					
					mMessages.add(message);
				}
			}
			else {
				System.err.println("Unknow field in object XML: " + nodeName);
			}
		}	
	}

	public Vector<Message> getMessages() {
		return mMessages;
	}

	public void setMessages(Vector<Message> mMessages) {
		if(mMessages == null)
			this.mMessages = new Vector<Message>();
		else
			this.mMessages = mMessages;
	}

	@Override
	public String createHTML() {
		StringBuilder sb = new StringBuilder();
		sb.append("<div class=\"holder\">");
		for (Message message : getMessages()) {
			sb.append("\n<div class=\"bookHolder\" >");
			sb.append("<strong>"+formatTime(message.getTime())+"</strong></br>");
			sb.append(message.getMessageText());				
			sb.append("</div>");
		}
		
		if(getMessages().isEmpty())
			sb.append("<center><h3>No Messages</h3></center>");

		sb.append("</div></center></body>");
		return HTTPUtils.HTMLPageHeader("") + sb;
	}
	
	public String formatTime(long time) {
		time = time / 1000;
		String seconds = Integer.toString((int) (time % 60));
		String minutes = Integer.toString((int) ((time % 3600) / 60));
		int hoursInt = (int)(time / 3600);
		int devide = ((int)hoursInt % 24)-4;
		
		String hours = Integer.toString(devide);

		if (seconds.length() < 2) {
			seconds = "0" + seconds;
		}
		if (minutes.length() < 2) {
			minutes = "0" + minutes;
		}
		if (hours.length() < 2) {
			hours = "0" + hours;
		}
		return hours+":"+minutes+":"+seconds;
	}
}
